<template>
  <div class="app-container">
    <el-switch
    style="margin-bottom:50px"
    v-model="type"
    @change="changeType"
    active-color="#409eff"
    active-text="开启黑名单监控"
    inactive-color="#dcdfe6"
    inactive-text="关闭黑名单监控"
    active-value=1
    inactive-value=0>
  </el-switch>
    <form-filter :triggerGroup="triggerGroup" :userLevelList="userLevelList" @on-filter="submitFilterForm" style="margin-bottom:30px;"/>

    <div class="btn-container">
      <el-button
        type="primary"
        size="small"
        @click="batchLock"
        v-if="roleCheck('blacklist-batch-lock')"
      >
        批量锁定
      </el-button>
      <!--      <el-button type="primary" size="small" @click="batchMemberLevelChange">批量调整会员层级</el-button>-->
      <el-button
        plain
        size="small"
        @click="setAllRead"
        v-if="roleCheck('blacklist-read-all')"
      >
        全部已读
      </el-button>
    </div>

    <div class="table-container">
      <el-table
        border
        :data="tableData.list"
        v-loading="loading"
        element-loading-text="加载中..."

        @selection-change="handleSelectionChange">
        >
        <el-table-column type="selection" width="55" align="center" :selectable="checkSelectable">
        </el-table-column>
        <el-table-column align="center" label="行为时间" width="180" prop="createTime" >
          <template slot-scope="{row}">
            {{row.createTime | toTime('YYYY-MM-DD HH:mm:ss')}}
          </template>
        </el-table-column>
        <el-table-column label="账号" width="160" align="center">
          <template slot-scope="{row}">
              <span v-if="!row.usernameRisk">--</span>
              <span v-if="row.usernameRisk&&row.behavior!=1" class="name" :class="row.usernameLevelRegister != 1 && row.usernameRisk&&row.usernameHit?'danger':'blue'" @click="showMember(row)">{{`${row.usernameRisk}:${toLevelStr(row.usernameLevelRegister)}`}}</span>
              <span v-if="row.usernameRisk&&row.behavior==1"  >{{`${row.usernameRisk}:${toLevelStr(row.usernameLevelRegister)}`}}</span>
          </template>
        </el-table-column>
        <el-table-column label="IP" width="160" align="center">
          <template slot-scope="{row}">
              <span :class="row.ipLevelRegister != 1 &&row.ipRisk&&row.ipHit ? 'danger' : ''">
                {{row.ipRisk ? (`${row.ipRisk}:${toLevelStr(row.ipLevelRegister)}`) : '--'}}
              </span>
          </template>
        </el-table-column>
        <el-table-column label="设备号" width="160" align="center">
          <template slot-scope="{row}">
              <span :class="row.deviceIdLevelRegister != 1&& row.deviceIdRisk &&row.deviceIdHit? 'danger' : ''">
                {{row.deviceIdRisk ? (`${row.deviceIdRisk}:${toLevelStr(row.deviceIdLevelRegister)}`) : '--'}}
              </span>
          </template>
        </el-table-column>
        <el-table-column label="银行卡" width="160" align="center">
          <template slot-scope="{row}">
              <span :class="row.bankLevelRegister != 1 &&row.bankCardRisk &&row.bankCardHit? 'danger' : ''">
                {{row.bankCardRisk ? (`${row.bankCardRisk}:${toLevelStr(row.bankCardLevelRegister)}`) : '--'}}
              </span>
          </template>
        </el-table-column>
        <el-table-column label="手机号" width="160" align="center">
          <template slot-scope="{row}">
              <span :class="row.mobileLevelRegister != 1 &&row.mobileRisk &&row.mobileHit? 'danger' : ''">
                {{row.mobileRisk ? (`${row.mobileRisk}:${toLevelStr(row.mobileLevelRegister)}`) : '--'}}
              </span>
          </template>
        </el-table-column>
        <el-table-column label="姓名"  width="160" align="center">
          <template slot-scope="{row}">
              <span :class="row.realNameLevelRegister != 1 &&row.realNameRisk&&row.realNameHit ? 'danger' : ''">
                {{row.realNameRisk ? (`${row.realNameRisk}:${toLevelStr(row.realNameLevelRegister)}`) : '--'}}
              </span>
          </template>
        </el-table-column>
        <el-table-column label="会员层级" prop="userLevelName" width="120" align="center">
          <template slot-scope="{row}">
            <span v-if="row.userLevelName">{{row.behavior==1?'--':row.userLevelName}}</span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column label="行为" width="120" align="center">
          <template slot-scope="{row}">
            <span>{{toBehaviorStr(row.behavior)}}</span>
          </template>
        </el-table-column>
        <el-table-column label="金额" prop="amount" width="130" align="center">
           <template slot-scope="{row}">
            <span v-if="row.amount">{{row.amount | currency}}</span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column label="单号" prop="orderId" width="130" align="center">
           <template slot-scope="{row}">
            <span>{{row.orderId || '--'}}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否已读" prop="readed" width="120" align="center">
          <template slot-scope="{row}">
            <span>{{toReadStr(row.readed)}}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template slot-scope="{row}">
            <el-button v-if="row.readed === 0 && roleCheck('to-read')" type="text" @click="setReaded(row.id)">设为已读</el-button>
            <el-button
              v-if="roleCheck('adjust-correlation-level')"
              type="text"
              @click="adjustLevel(row.id)"
            >
              调整关联群组
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination background @size-change="gridSizeChange" @current-change="gridCurrentChange"
                     :current-page="filters.page" :page-sizes="gridPageSize" :page-size="filters.size"
                     :layout="gridLayout" :total="tableData.total">
      </el-pagination>
    </div>

    <!--  调整关联等级弹窗  -->
    <change-level-dialog
      v-if="dialogName === staticDialogName1"
      :adjustId="adjustData.id"
      :dialogVisible="dialogVisible"
      :dialogTableData="dialogTableData"
      :triggerGroup="triggerGroup"
      @cancel="cancel">
    </change-level-dialog>

    <!--  批量锁定弹窗  -->
    <account-lock-dialog
      v-if="dialogName === staticDialogName2"
      :lockClass="lockClass"
      :lockName="lockName"
      v-model="dialogVisible"
      @submit="batchLockSubmit"
      @cancel="cancel">
    </account-lock-dialog>
  </div>
</template>

<script>
import FormFilter from './formFilter';
import { grid, dialog } from '@/build';
import ChangeLevelDialog from './changeLevel';
import AccountLockDialog from './accountLockDialog';
import {
  risBlackListBehaviorApi,
  risBlackListGetLevelApi,
  risBlackListSetReadedApi,
  risBlackListSetAllReadedApi,
  risBlackListBehaviorLevelApi,
  blackSwitch,
  getSwitchType,
} from '@/services/api/risk';
import { setMembersStatus } from '@/services/api/member';
import { getUserLevelList } from '@/services/api/userLevel';
import { getMonitorNum } from '@/services/api/message';

export default {
  name: 'behavior-monitor',
  components: {
    FormFilter,
    ChangeLevelDialog,
    AccountLockDialog,
  },
  mixins: [grid, dialog],
  data() {
    return {
      monitorData: {},
      lockName: [], // 批量锁定的账号
      type: null, // 黑名单开关 默认关闭
      staticDialogName1: 'change-level-dialog',
      staticDialogName2: 'batch-lock-dialog',
      dialogVisible: false,
      multipleSelection: [],
      tableData: {
        list: [],
      },
      loading: false,
      filters: {
        deviceId: '',
        username: '',
        level: [],
        deviceNumber: '',
        blackIp: '',
        bankCard: '',
        mobile: '',
        realName: '',
        userLevelId: -1,
        orderId: '',
        readed: -1,
        behavior: [0, 1, 2, 3, 4],
        startDate: moment().format('YYYY-MM-DD 00:00:00'),
        endDate: moment().format('YYYY-MM-DD 23:59:59'),
        page: 1,
        size: 20,
      },
      dialogName: 'change-level-dialog',

      form: {},
      dialogTableData: [],
      adjustData: {
        id: undefined,
      },
      setReadedData: {
        id: undefined,
      },
      triggerGroup: [],
      userLevelList: [],
      lockClass: 1,
      lockForm: {},
    };
  },
  methods: {
    changeType() {
      this.doGet({ action: 'switchType' });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    checkSelectable(row) {
      return row.behavior != 1;
    },
    // 批量锁定
    batchLock() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          type: 'warning',
          message: '请选中需要处理的数据',
        });
        return;
      }
      this.lockName = _.map(this.multipleSelection, item => item.usernameRisk);
      this.dialogVisible = true;
      this.openDialog({ props: {}, dialogName: 'batch-lock-dialog' });
    },
    // 全部设为已读
    setAllRead() {
      // this.openDialog({ props: {}, dialogName: this.dialogName });
      this.doGet({ action: 'setAllReaded' });
    },
    cancel() {
      this.dialogVisible = false;
      this.dialogName = undefined;
    },
    setReaded(id) {
      this.setReadedData.id = id;
      this.doGet({ action: 'setItemReaded' });
    },
    adjustLevel(id) {
      this.dialogVisible = true;
      this.openDialog({ props: {}, dialogName: 'change-level-dialog' });
      this.adjustData.id = id;
      this.doGet({ action: 'getAllLevel' });
    },
    toLevelStr(val) {
      const levelStr = _.find(this.triggerGroup, { levelId: val });
      return levelStr ? `${levelStr.levelName}(${levelStr.remark})` : '';
    },
    toBehaviorStr(val) {
      const behaviorStr = _.find(consts.BLACK_LIST_BEHAVIOR, { value: val });
      return behaviorStr ? behaviorStr.title : '';
    },
    toReadStr(val) {
      const readStr = _.find(consts.BLACK_LIST_READ, { value: val });
      return readStr ? readStr.title : '';
    },
    batchLockSubmit(lockForm) {
      if (lockForm.type.includes(7)) {
        lockForm.type = 7;
      } else {
        lockForm.type = lockForm.type.join(',');
      }
      lockForm.ids = _.map(this.multipleSelection, item => item.userId);
      lockForm.lockClass = this.lockClass;
      this.lockForm = { ...lockForm };
      this.doSave({ action: 'saveLock' });
    },
    // 跳转到用户详情Tabs
    showMember(member) {
      let name = '';
      if (member.userType == 0) {
        name = 'member-list';
      } else if (member.userType == 1) {
        name = 'agency-list';
      }
      this.$router.push({
        name,
        query: {
          add: true,
          tagNo: this.lastTagNo + 1,
        },
        params: {
          member,
        },
      });
    },
    submitFilterForm(formInline) {
      // console.log(`,,,,${JSON.stringify(formInline)}`);
      const { time } = formInline;
      if (!_.isUndefined(time) && _.isArray(time)) {
        [this.filters.startDate, this.filters.endDate] = time;
      } else {
        this.filters.startDate = undefined;
        this.filters.endDate = undefined;
      }

      this.filters = { ...this.filters, ...formInline };
      // this.filters.level = this.filters.level.join(',');
      this.doGet({ action: 'getGrid' });
    },
  },
  computed: {
    ...mapState({
      lastTagNo: state => state.tagsView.lastTagNo,
    }),
  },
  mounted() {
    this.bindGet(getSwitchType, '', {
      action: 'getType',
      format: (data) => {
        this.type = data.type;
        console.log(`按钮状态::${this.type}`);
        return data;
      },
    });
    this.getAll();
    // 获取列表
    this.bindGet(risBlackListBehaviorApi, 'tableData', {
      action: 'getGrid',
      sendingData: 'filters',
      beforeSend: (data) => {
        if (data) {
          if (data.level.length > 0) {
            data.level = data.level.join(',');
          }
          if (data.behavior.length > 0) {
            data.behavior = data.behavior.join(',');
          }
        }
        return data;
      },
    });
    // 获取调整关联等级弹窗数据
    this.bindGet(risBlackListGetLevelApi, 'dialogTableData', {
      action: 'getAllLevel',
      sendingData: 'adjustData',
      callback: ([result, data]) => {
        if (data) {
          const list = [];
          _.each(data, (item, index) => {
            const { levelNow } = item;
            const temp = item.content.split(':')[1];
            item.levelId = levelNow;
            item.changeLevelID = undefined;
            item.index = index;
            item.isDisable = temp === '-';
            list.push(item);
          });
          this.dialogTableData = list;
        }
      },
    });
    // 单个设为已读
    this.bindGet(risBlackListSetReadedApi, '', {
      action: 'setItemReaded',
      sendingData: 'setReadedData',
      callback: ([result, data]) => {
        if (result) {
          this.$message({
            type: 'success',
            message: '成功设置为已读',
          });
          this.gridSearch();
          this.doGet({ action: 'getMonitor' });
        }
      },
    });
    // 全部已读
    this.bindGet(risBlackListSetAllReadedApi, '', {
      action: 'setAllReaded',
      successMessage: '设置成功',
      callback: ([result, data]) => {
        if (result) {
          this.gridSearch();
          this.doGet({ action: 'getMonitor' });
        }
      },
    });
    // 监控消息
    this.bindGet(getMonitorNum, 'monitorData', {
      action: 'getMonitor',
      callback: ([result, data]) => {
        if (result) {
          this.$store.commit(types.GET_BLACK_COUNT, data.unreadCount);
        }
      },
    });
    // 获取触发群组
    this.bindGet(risBlackListBehaviorLevelApi, '', {
      action: 'getLevelList',
      callback: ([result, data]) => {
        if (data) {
          this.triggerGroup = data;
          _.forEach(data, (item) => {
            this.filters.level.push(item.levelId);
          });
        }
        // this.submitFilterForm(this.filters);
        this.gridSearch();
      },
    });
    // 获取会员层级下拉
    this.bindGet(getUserLevelList, 'userLevelList', {
      action: 'getUserLevelList',
    });
    // 批量锁定
    this.bindSave(setMembersStatus, 'saveLock', 'lockForm', {
      callback: ([result, data]) => {
        this.dialogVisible = false;
        if (result) {
          if (data) {
            if (data.failNum > 0 && [3, 4].indexOf(this.lockClass) != -1) {
              this.$message({
                type: 'success',
                message: `${this.lockClass == 3 ? '锁定' : '解锁'}失败,失败原因：${data.failMessage}`,
              });
            }

            if (data.failNum > 0 && data.successNum < 1 && [3, 4].indexOf(this.lockClass) == -1) {
              this.$message({
                type: 'success',
                message: `失败批量${this.lockClass == 1 ? '锁定' : '解锁'}${data.failNum}个操作,失败原因：${data.failMessage}`,
              });
            } else if (data.failNum > 0 && data.successNum > 0 && [3, 4].indexOf(this.lockClass) == -1) {
              this.$message({
                type: 'success',
                message: `成功批量${this.lockClass == 1 ? '锁定' : '解锁'}${data.successNum}个操作，失败批量${this.lockClass == 1 ? '锁定' : '解锁'}${data.failNum}个操作,失败原因：${data.failMessage}`,
              });
            } else if (data.failNum < 1 && data.successNum > 0 && [3, 4].indexOf(this.lockClass) == -1) {
              this.$message({
                type: 'success',
                message: `成功批量${this.lockClass == 1 ? '锁定' : '解锁'}${data.successNum}个操作`,
              });
            }
          }
          this.gridSearch();
        }
      },
    });
    this.doGet({ action: 'getLevelList' });
    this.doGet({ action: 'getUserLevelList' });
    this.bindGet(blackSwitch, '', {
      action: 'switchType',
      sendingData: 'type',
      beforeSend: data => ({
        type: this.type,
      }),
      callback: ([result]) => {
        if (result) {
          if (this.type == 0) {
            this.$message({
              type: 'success',
              message: '关闭成功',
            });
          } else {
            this.$message({
              type: 'success',
              message: '开启成功',
            });
          }
        }
      },
    });
  },
};
</script>

<style lang="scss" scoped>
  .app-container {
    .btn-container {
      overflow: hidden;

      button {
        float: left;

        &:last-child {
          float: right;
        }
      }
    }
    .table-container {
      margin-top: 20px;

      .name {
        text-decoration: underline;
        cursor: pointer;
      }

      .danger {
        color: #FF0000;
      }
      .blue{
        color:#409eff;
      }
    }
  }
</style>
